package grpc

import (
	"context"
	"dogapm"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	pb "proto"
	"skusvc/dao"
)

type SkuServer struct {
	pb.UnimplementedSkuServiceServer
}

// DecreaseStock 扣减库存服务
func (s *SkuServer) DecreaseStock(ctx context.Context, sku *pb.Sku) (*pb.Sku, error) {
	info, ok := dao.SkuDao.Get(sku.Id)
	if !ok {
		dogapm.Logger.Error(ctx, "DecreaseStock", map[string]interface{}{
			"msg": "sku not found",
			"sku": sku.Id,
		}, nil)
		return nil, status.Errorf(codes.NotFound, "sku not exits")
	}
	ok, err := dao.SkuDao.Decr(sku.Id, sku.Num)
	if err != nil {
		dogapm.Logger.Error(ctx, "DecreaseStock", map[string]interface{}{
			"msg": "decrease stock failed",
			"sku": sku.Id,
			"err": err.Error(),
		}, err)
		return nil, status.Errorf(codes.Internal, "decrease stock failed")
	}

	return &pb.Sku{
		Name:  info.Name,
		Id:    int64(info.ID),
		Price: info.Price,
		Num:   sku.Num,
	}, nil
}
